//
//  XGSettingItem.m
//  Lottery
//
//  Created by monkey on 2018/10/4.
//  Copyright © 2018 itcast. All rights reserved.
//

#import "XGSettingItemModel.h"

@implementation XGSettingItemModel
{
    /// 是否已经加载
    BOOL  _isloaded;
}

// 同时实现set和get方法 系统不会再自动生成成员变量 可以使用@synthesize 手动生成
@synthesize switchState = _switchState;
@synthesize subTitle = _subTitle;

- (BOOL)switchState
{
    // 如果有开关 从缓存中读取开关状态 为了节约性能 只读取一次
    if (!_isloaded && [self.accessoryType isEqualToString:@"UISwitch"]) {
        _switchState = [[NSUserDefaults standardUserDefaults] boolForKey:self.title];
        _isloaded = YES;
    }

    return _switchState;
}

- (void)setSwitchState:(BOOL)switchState
{
    _switchState = switchState;
    
    // 状态改变 开关状态重新保存到缓存中
    [[NSUserDefaults standardUserDefaults] setBool:switchState forKey:self.title];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (NSString *)subTitle
{
    if (!_isloaded && [_subTitle isEqualToString:@"00:00:00"]) {
        _subTitle = [[NSUserDefaults standardUserDefaults] objectForKey:self.title];
        _isloaded = YES;
        _subTitle = _subTitle ? _subTitle : @"00:00:00";
    }
    
    return _subTitle;
}

- (void)setSubTitle:(NSString *)subTitle
{
    _subTitle = subTitle;

    // 如果是时间字符串 且 不是默认字符串 保存起来
    if ([self isTimeString:subTitle] && ![subTitle isEqualToString:@"00:00:00"]) {
        [[NSUserDefaults standardUserDefaults] setObject:subTitle forKey:self.title];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}

// 判断一个字符串是否是时间
- (BOOL)isTimeString:(NSString *)str
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"HH:mm";
    NSDate *date = [formatter dateFromString:str];
    return date != nil;
}

@end
